package com.panda.controller.cos;

import com.panda.utils.RespondResult;
import com.tencent.cloud.CosStsClient;
import com.tencent.cloud.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.TreeMap;

/**
 * 腾讯COS API文档 https://cloud.tencent.com/document/product/436/14048
 */
@RestController
@ConfigurationProperties(prefix = "panda")
@Api(tags = "获取对象存储临时密钥接口")
public class Cos {

    private String ID;
    private String KEY;

    public void setID(String ID) {
        this.ID = ID;
    }

    public void setKEY(String KEY) {
        this.KEY = KEY;
    }

    @ApiOperation("获取密钥")
    @GetMapping("/credential")
    public RespondResult credential() {
        System.out.println("获取密钥了。。。");
        TreeMap<String, Object> config = new TreeMap<>();
        Response response;
        try {
            // 云 api 密钥 SecretId
            config.put("secretId", ID);
            // 云 api 密钥 SecretKey
            config.put("secretKey", KEY);

            // 设置域名
            //config.put("host", "sts.internal.tencentcloudapi.com");

            // 临时密钥有效时长，单位是秒
            config.put("durationSeconds", 1800);

            // 换成你的 bucket
            config.put("bucket", "panda-1308597681");
            // 换成 bucket 所在地区
            config.put("region", "ap-guangzhou");

            // 可以通过 allowPrefixes 指定前缀数组, 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            config.put("allowPrefixes", new String[]{
                    "video/*", "avatar/*", "image/*"
            });

            // 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            String[] allowActions = new String[]{
                    // 简单上传
                    "name/cos:PutObject",
                    "name/cos:PostObject",
                    // 删除
                    "name/cos:RemoveObject",
                    // 分片上传
                    "name/cos:InitiateMultipartUpload",
                    "name/cos:ListMultipartUploads",
                    "name/cos:ListParts",
                    "name/cos:UploadPart",
                    "name/cos:CompleteMultipartUpload"
            };
            config.put("allowActions", allowActions);
            response = CosStsClient.getCredential(config);
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("no valid secret !");
        }
        return RespondResult.okResult(response);
    }
}
